//
//  WebAPI.m
//  WeChatHelper
//
//  Created by bang yi bang on 14-3-20.
//  Copyright (c) 2014年 bang yi bang. All rights reserved.
//

#import "WebAPI.h"


static AFHTTPRequestOperationManager *requestManager;
@interface WebAPI ()
{
    
}
@end

@implementation WebAPI
//@synthesize manager = requestManager;

+ (WebAPI *) defaultManager
{
    return [[self alloc] init];
}

- (id) init {
    self = [super init];
    if (self) {
        static dispatch_once_t onceToken ;
        dispatch_once (&onceToken,^{
            requestManager = [AFHTTPRequestOperationManager manager];
        });
    }
    return self;
}

- (void) setResponseSerializer:(AFHTTPResponseSerializer *)serializer
{
    requestManager.responseSerializer = serializer;
}

- (void) setHeader:(NSString *)value forKey:(NSString *)key
{
    [requestManager.requestSerializer setValue:value forHTTPHeaderField:key];
}

- (void) postWebAPI:(NSDictionary *)params withPath:(NSString *)path andMethodNode:(NSString *)node completed:(WebAPIBlockRequest)complete
{
    _complete = complete;
    NSString *url = [NSString stringWithFormat:@"%@/%@",path,node];
    [requestManager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_complete) {
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            _complete(1,operation,resultDic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (_complete) {
            _complete(-1,operation,nil);
            
            [SVProgressHUD showErrorWithStatus:@"网络连接失败"];
        }
    }];
}
- (void) getWebAPIWithPath:(NSString *)path andParams:(NSDictionary *)params andMethodNode:(NSString *)node  completed:(WebAPIBlockRequest)complete {
   
   
   
    _complete = complete;
     NSString *url = [NSString stringWithFormat:@"%@/%@",path,node];
     url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
     dispatch_queue_t queue = dispatch_queue_create("异步刷新", nil);
     dispatch_async(queue, ^(void) {
    [requestManager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_complete) {
            
            NSDictionary *resultDic;
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                resultDic =  responseObject;
            }else if([responseObject isKindOfClass:[NSData class]]){
                
                resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            }
            
            if (resultDic) {
                _complete(1,operation,resultDic);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (_complete) {
            _complete(-1,operation,nil);
            
            NSLog(@"error:%@",error);
            [SVProgressHUD showErrorWithStatus:@"网路连接失败"];
        }
    }];
     });
}

- (void)getWebAPIWithParams:(NSDictionary *)params andMethodNode:(NSString *)node completed:(WebAPIBlockRequest)complete {
    dispatch_queue_t queue = dispatch_queue_create("异步刷新", nil);
    dispatch_async(queue, ^(void) {
        
        _complete = complete;
        NSString *url = [NSString stringWithFormat:@"%@/%@",kUrl,node];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        
        [requestManager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (_complete) {
                
                NSDictionary *resultDic;
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    resultDic =  responseObject;
                }else if([responseObject isKindOfClass:[NSData class]]){
                    
                    resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                }
                
                if (resultDic) {
                    _complete(1,operation,resultDic);
                }
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (_complete) {
                _complete(-1,operation,nil);
                
                NSLog(@"error:%@",error);
                [SVProgressHUD showErrorWithStatus:@"网路连接失败"];
            }
        }];
    });
}

- (void)getWebAPIWithPath:(NSString *)path andParams:(NSDictionary *)params  completed:(WebAPIBlockRequest)complete {
    _complete = complete;
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_complete) {
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            _complete(1,operation,resultDic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (_complete) {
            _complete(-1,operation,nil);
        }
    }];
}

- (void) getWebAPIWithUrl:(NSString *)url  completed:(WebAPIBlockRequest)complete {
    _complete = complete;
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_complete) {
            _complete(1,operation,responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (_complete) {
            _complete(-1,operation,nil);
        }
    }];
}

/**
 *  登陆
 */
- (void)logInWithUserName:(NSString *)name andPassword:(NSString *)password completed:(WebAPIBlockRequest)complete
{
    WebAPI *webAPI=[WebAPI defaultManager];
    [webAPI setHeader:@"text/html; charset=utf-8" forKey:@"Content-Type"];
    
    [webAPI setResponseSerializer:[AFHTTPResponseSerializer serializer]];

    NSDictionary *parm=@{@"USER_NAME": name,@"USER_PASSWORD": password};
    NSString *url=[NSString stringWithFormat:@"%@/%@",kUrl,@"Login"];

    
     //[webAPI postWebAPI:parm withPath:kUrl andMethodNode:@"Login" completed:complete];
    [webAPI getWebAPIWithPath:url andParams:parm completed:complete];
    
    [QLPropertyUtils putStringByKey:@"account" value:name];
    [QLPropertyUtils putStringByKey:@"password" value:password];
}

//屡次登录
-(void)loginIn:(NSString *)userName andPw:(NSString *)password{

        [self logInWithUserName:userName andPassword:password completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
            
            if (state==1&&responseObject) {
                
                
                NSString *msg=[NSString stringWithFormat:@"%@",responseObject[@"MESSAGE_INFO"][@"CODE"]];
                
                if ([msg isEqualToString:@"0000"]) {
                    
                    
                    [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                    //去用户id
                    NSString *idString=responseObject[@"LOGIN_USER_RSP"][@"UPLOAD_URL"];
                    NSArray *idArr=[idString componentsSeparatedByString:@"?userId="];
                    ApplicationDelegate.currentUserId=[idArr lastObject];
                    ApplicationDelegate.uploadUrl = [NSURL URLWithString:idString];
                    [NSStandardUserDefaults setObject:userName forKey:@"USER_NAME"];
                    [NSStandardUserDefaults setObject:password forKey:@"USER_PASSWORD"];
                    [NSStandardUserDefaults setObject:[idArr lastObject] forKey:@"USER_ID"];
                    [NSStandardUserDefaults setObject:idString forKey:@"USER_URL"];
                    [NSStandardUserDefaults synchronize];
                    ApplicationDelegate.userName=userName;
                    
                    
                }
                
            }
            
            
        }];
}

@end
